using System.Data.Objects;
using Common.Core;
using Common.Unity.Extensions;
using Microsoft.Practices.ObjectBuilder2;
using Guard=Microsoft.Practices.ObjectBuilder2.Guard;

namespace Common.Unity.Extensions.Entity
{
	public class ObjectParameterCreator
	{
		readonly string name;
		readonly object source;

		public ObjectParameterCreator( string name ) : this( name, null )
		{}

		public ObjectParameterCreator( string name, object source )
		{
			Guard.ArgumentNotNullOrEmpty( name, "name" );
			this.name = name;
			this.source = source;
		}

		public ObjectParameter CreateParameter( IBuilderContext context )
		{
			object value = ResolveValue( context );
			return value != null ? new ObjectParameter( name, value ) : null;
		}

		object ResolveValue( IBuilderContext context )
		{
			object 
				item = context.GetBuildSource() ?? source,
				result = item != null ? new ValueResolver( item, name ).Resolve() : null;
			return result;
		}
	}
}